<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <p>
        <a-form layout="inline" :model="param">
          <a-form-item>
            <a-input-search
                v-model:value="param.name"
                placeholder="名称"
                enter-button
                @search="handleQuery({page: 1, size: pagination.pageSize})"
            />
          </a-form-item>
          <!--<a-form-item>-->
          <!--  <a-input v-model:value="param.name" placeholder="名称">-->
          <!--  </a-input>-->
          <!--</a-form-item>-->
          <!--<a-form-item>-->
          <!--  <a-button type="primary" @click="handleQuery({page: 1, size: pagination.pageSize})">-->
          <!--    查询-->
          <!--  </a-button>-->
          <!--</a-form-item>-->
          <a-form-item>
            <a-button type="primary" @click="add()">
              新增
            </a-button>
          </a-form-item>
        </a-form>
      </p>
      <a-table
          :columns="columns"
          :data-source="level1"
          :row-key="record => record.id"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
          class="components-table-demo-nested"
      >
        <template #bodyCell="{ column, record }">
          <!--<template v-slot:category="{ text, record }">-->
          <!--  <span>{{ getCategoryName(record.category1Id) }} / {{ getCategoryName(record.category2Id) }}</span>-->
          <!--</template>-->
          <template v-if="column.key === 'action'">
            <a-space size="small">
<!--              <router-link :to="'/admin/doc?categoryId=' + record.id">-->
<!--                <a-button type="primary">-->
<!--                  文档管理-->
<!--                </a-button>-->
<!--              </router-link>-->
              <a-button type="primary" @click="edit(record)">
                编辑
              </a-button>
              <a-popconfirm
                  title="删除后不可恢复，确认删除?"
                  ok-text="是"
                  cancel-text="否"
                  @confirm="handleDelete(record.id)"
              >
                <a-button type="danger">
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>

        </template>
      </a-table>
    </a-layout-content>
  </a-layout>


  <a-modal
      title="分类表单"
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleModalOk"
      ok-text="保存"
      cancel-text="取消"
  >
    <a-form :model="category" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="名称">
        <a-input v-model:value="category.name" />
      </a-form-item>
      <a-form-item label="父分类">
<!--        <a-input v-model:value="category.parent" placeholder="请输入描述信息" allow-clear />-->
        <a-select
            v-if="category.parent === 0" value="无"
        >
          <a-select value="0">无</a-select>
          <a-select v-for="c in level1" :key="c.id" :value="c.id" :disabled="category.id === c.id">
            {{c.name}}
          </a-select>
        </a-select>
          <a-select
              v-else v-model:value="category.parent"
          >
          <a-select value="0">无</a-select>
          <a-select v-for="c in level1" :key="c.id" :value="c.id" :disabled="category.id === c.id">
            {{c.name}}
          </a-select>
        </a-select>
      </a-form-item>
      <a-form-item label="顺序">
        <a-input v-model:value="category.sort" placeholder="请输入描述信息" allow-clear />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import axios from 'axios';
import { message } from 'ant-design-vue';
import { Tool } from '@/util/tool';

export default defineComponent({
  name: 'AdminCategory',
  setup() {
    const param = ref();
    param.value = {};
    const categorys = ref();
    /**
     * 一级分类树，children属性就是二级分类
     * [{
     *   id: "",
     *   name: "",
     *   children: [{
     *     id: "",
     *     name: "",
     *   }]
     * }]
     */
    const level1 = ref([{}]);
    const pagination = ref({
      onChange: (page: number) => {
        console.log(page);
      },
      current: 1,
      pageSize: 200,
      total: 0,
      // showSizeChanger: true
    });
    const loading = ref(false);

    const columns = [
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
        width: 300
      },
      {
        title: '父分类',
        dataIndex: 'parent',
        key: 'parent',
        align: 'center'
        // slots: { customRender: 'category' }
      },
      {
        title: '顺序',
        dataIndex: 'sort',
        key: 'sort',
        align: 'center'
      },{
        title: 'Action',
        dataIndex: 'action',
        key: 'action',
        align: 'center',
        width: 500
      }
    ];
    const innerColumns = [{
      title: '描述',
      dataIndex: 'description',
      key: 'description'
      // slots: { customRender: 'cover' }
    },
      ];
    /**
     * 数据查询
     **/
    const handleQuery = (params: any) => {
      loading.value = false;
      // 如果不清空现有数据，则编辑保存重新加载数据后，再点编辑，则列表显示的还是编辑前的数据
      level1.value = [];
      axios.get("/category/list", {
        params: {
          page: params.page,
          size: params.size,
          name: param.value.name
        }
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          // message.success(data.message);
          categorys.value = data.content.list;
          level1.value = [];
          level1.value = Tool.array2Tree(data.content.list, 0);
          // 重置分页按钮
          pagination.value.current = params.page;
          pagination.value.pageSize = params.size;
          pagination.value.total = data.content.total;
        } else {
          message.error(data.message);
        }
      });
    };

    /**
     * 表格点击页码时触发
     */
    const handleTableChange = (pagination: any) => {
      console.log("看看自带的分页参数都有啥：" + pagination);
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize
      });
    };

    // -------- 表单 ---------
    /**
     * 数组，[100, 101]对应：前端开发 / Vue
     */
    const category = ref({});
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const handleModalOk = () => {
      modalLoading.value = true;
      axios.post("/category/save", category.value).then((response) => {
        modalLoading.value = false;
        const data = response.data; // data = commonResp
        if (data.success) {
          modalVisible.value = false;
          message.success(data.message);
          // 重新加载列表
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize,
          });
        } else {
          message.error(data.message);
        }
      });
    } ;

    /**
     * 编辑
     */
    const edit = (record: any) => {
      modalVisible.value = true;
      //解决交互式参数实时变化的问题，编辑表表单未提交表格参数实时发生变化
      category.value = Tool.copy(record);
      // categoryIds.value = [category.value.category1Id, category.value.category2Id]
    };
    /**
     * 新增
     */
    const add = () => {
      modalVisible.value = true;
      category.value = {};
    };
    const handleDelete = (id: string) => {
      console.log(
          "id========"+id
      );
      axios.delete("/category/delete/"+id).then((response) => {
        const data = response.data; // data = commonResp
        if (data.success) {
          message.success('Delete on Yes');
          // 重新加载列表
          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize,
          });
        } else {
          message.error(data.message);
        }
      });

    }

    onMounted(() => {
      handleQuery({
        page: 1,
        size: pagination.value.pageSize
      })
    });

    return {
      param,
      categorys,
      pagination,
      columns,
      innerColumns,
      loading,
      handleTableChange,
      handleQuery,

      edit,
      add,

      modalVisible,
      modalLoading,
      handleModalOk,
      handleDelete,
      category,
      level1,
    }
  }
});
</script>

<style scoped>
img {
  width: 50px;
  height: 50px;
}
</style>
